package org.cqc.aop;

import com.sun.org.apache.xml.internal.serialize.Method;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.cqc.utils.JsonUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author caoqc
 * @Description:
 * @date 2022/02/07 09:57:47
 */
@Aspect
@Configuration
@Slf4j
public class LogAop {
    @Pointcut("execution(* org.cqc.controller..*.*(..))")
    public void pintCut() {
    }

    @Around("pintCut()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        String url = request.getRequestURI();
        String method = request.getMethod();
        String queryString = request.getQueryString();
        Map map = request.getParameterMap();
        log.info("***************************************************");
        log.info("请求开始");
        log.info("请求地址:[{}]", url);
        log.info("请求参数:[{}]", queryString);
        if ("POST".equals(method)) {
            log.info("请求内容:[{}]", ReadAsChars(request));
        }

        Object result = pjp.proceed();
        log.info("请求返回值:[{}] ", JsonUtil.objectToJson(result));
        log.info("请求结束");
        log.info("***************************************************");
        return result;
    }


    public static String ReadAsChars(HttpServletRequest request) {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder("");
        try {
            br = request.getReader();
            String str;
            while ((str = br.readLine()) != null) {
                sb.append(str);
            }
            br.close();
        } catch (IOException e) {
            log.error("[{}]", e);
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    log.error("[{}]", e);
                }
            }
        }
        return sb.toString();
    }

}
